package br.com.rubrol.controller;

 import java.util.ArrayList;
import java.util.List;

import javax.faces.event.ActionEvent;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.rubrol.bean.Tab;
import br.com.rubrol.bean.TipoOperacao;
import br.com.rubrol.model.Maquina;
import br.com.rubrol.util.HibernateUtil;
import br.com.rubrol.util.MessageBundleLoader;

import com.icesoft.faces.component.ext.RowSelectorEvent;

public class CadastroMaquinaBean extends AbstractBaseBean {
	private static final long serialVersionUID = 1L;
	private int tabIndex = -1;
	private List<Tab> tabs;

	// Beans properties
	private Long codigo;
	private String nome;
	private String modelo;

	// List Entities
	private List<Maquina> entities;
	
	//Management properties
	private boolean adicionar,editar,excluir,salvar;
	private boolean txtCodigo,txtNome,txtMaquina;
	private TipoOperacao operacao;

	public CadastroMaquinaBean() {
	}

	public List<Tab> getTabs() {
		return tabs;
	}

	public void setTabs(List<Tab> tabs) {
		this.tabs = tabs;
	}

	public int getTabIndex() {
		return tabIndex;
	}

	public void setTabIndex(int tabIndex) {
		this.tabIndex = tabIndex;
	}

	public int getTabSize() {
		return tabs.size();
	}

	public Long getCodigo() {
		return codigo;
	}

	public void setCodigo(Long codigo) {
		this.codigo = codigo;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public String getModelo() {
		return modelo;
	}

	public void setModelo(String modelo) {
		this.modelo = modelo;
	}

	public List<Maquina> getEntities() {
		return entities;
	}

	public void setEntities(List<Maquina> entities) {
		this.entities = entities;
	}

	public boolean isAdicionar() {
		return adicionar;
	}

	public void setAdicionar(boolean adicionar) {
		this.adicionar = adicionar;
	}

	public boolean isEditar() {
		return editar;
	}

	public void setEditar(boolean editar) {
		this.editar = editar;
	}

	public boolean isExcluir() {
		return excluir;
	}

	public void setExcluir(boolean excluir) {
		this.excluir = excluir;
	}

	public boolean isSalvar() {
		return salvar;
	}

	public void setSalvar(boolean salvar) {
		this.salvar = salvar;
	}

	public boolean isTxtCodigo() {
		return txtCodigo;
	}

	public void setTxtCodigo(boolean txtCodigo) {
		this.txtCodigo = txtCodigo;
	}

	public boolean isTxtNome() {
		return txtNome;
	}

	public void setTxtNome(boolean txtNome) {
		this.txtNome = txtNome;
	}

	public boolean isTxtMaquina() {
		return txtMaquina;
	}

	public void setTxtMaquina(boolean txtMaquina) {
		this.txtMaquina = txtMaquina;
	}

	public void removeTab(ActionEvent event) {
		if (tabs != null && tabs.size() > tabIndex) {
			tabs.remove(tabIndex);
			if (tabIndex > 0) {
				tabIndex--;
			}
		}
	}

	public void addTab(ActionEvent event) {

	}

	@Override
	@SuppressWarnings("unchecked")
	public void initComponents() {
		// list Entities
		Session session = HibernateUtil.getSessionFactory().openSession();
		entities = session.createQuery(String.format("SELECT d FROM %s d ", Maquina.class.getName())).list();
		// Tabs
		tabs = new ArrayList<Tab>();
		Tab tabMain = new Tab(MessageBundleLoader.getMessage("cadastrommaquinas.form.title"), "", ++tabIndex);
		tabs.add(tabMain);
		//Management Beans
		travarCampos();
		operacao = TipoOperacao.NONE;

	}
	
	public void rowSelectionListener(RowSelectorEvent event) {
        Maquina entity;
        for(int i = 0, max = entities.size(); i < max; i++){
        	entity = (Maquina)entities.get(i);
            if (entity.isSelected() && operacao == TipoOperacao.NONE) { 
               codigo = entity.getCodigo();
               nome = entity.getNome();
               modelo = entity.getModelo();
               editar = false;
               excluir= false;
            }
        }
    }
	
	private void travarCampos(){
		txtCodigo = true;
		txtNome = true;
		txtMaquina = true;
		adicionar = false;
		editar = true;
		excluir = true;
		salvar = true;
	}
	private void destravarCampos(){
		txtCodigo = true;
		txtNome = false;
		txtMaquina = false;
		adicionar = true;
		editar = false;
		excluir = false;
		salvar = false;
	}
	private void limparCampos(){
		codigo = 0L;
		nome= "";
		modelo ="";
	}
	
	public void btnAdicionar(ActionEvent event){
		destravarCampos();
		editar = true;
		excluir = true;
		limparCampos();
		operacao = TipoOperacao.ADD;
	}
	
	public void btnEditar(ActionEvent event){
		destravarCampos();
		editar = true;
		excluir = true;
		operacao = TipoOperacao.EDIT;
	}
	
	public void btnCancelar(ActionEvent event){
		travarCampos();
		limparCampos();
		operacao = TipoOperacao.NONE;
	}
	
	@SuppressWarnings("unchecked")
	public void btnExcluir(ActionEvent event){
		Maquina entity= new Maquina(codigo,nome, modelo);
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		try {
			session.delete(session.merge(entity));
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		//Refresh in the list.
		entities = session.createQuery(String.format("SELECT d FROM %s d ", Maquina.class.getName())).list();
		limparCampos();
		travarCampos();
		operacao = TipoOperacao.NONE;
	}
	
	@SuppressWarnings("unchecked")
	public void btnSalvar(ActionEvent event){
		if(operacao == TipoOperacao.ADD){
			Maquina entity= new Maquina(nome, modelo);
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction tx = session.beginTransaction();
			try {
				session.save(entity);
				tx.commit();
			} catch (HibernateException e) {
				e.printStackTrace();
				tx.rollback();
			}
			//Refresh in the list.
			entities = session.createQuery(String.format("SELECT d FROM %s d ", Maquina.class.getName())).list();
		}else if(operacao == TipoOperacao.EDIT){
			Maquina entity= new Maquina(codigo,nome, modelo);
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction tx = session.beginTransaction();
			try {
				session.merge(entity);
				tx.commit();
			} catch (HibernateException e) {
				e.printStackTrace();
				tx.rollback();
			}
			//Refresh in the list.
			entities = session.createQuery(String.format("SELECT d FROM %s d ", Maquina.class.getName())).list();
		}
		limparCampos();
		travarCampos();
		operacao = TipoOperacao.NONE;
	}
	
	public String btnVoltar(){
		return "main";
	}
}
